// pages/shoppingMall/editAddress.js
const app = getApp()
var topOpacity = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "收货地址", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent',
      isShare: 0,
    },
    requestUrl: app.baseUrl,
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,
    btnText: '保存地址',
    isChecked: false,
    name: '',
    phone: '',
    address: '',
    num: '',
    openid: '',
    shareTitle: '',
    shareImg: '',
    id: 0
  },
  toggleSwitch() {
    this.setData({
      isChecked: !this.data.isChecked
    })
  },
  //收货人姓名
  nameIpt(e) {
    this.setData({
      name: e.detail.value
    })
  },
  //电话
  phoneIpt(e) {
    this.setData({
      phone: e.detail.value
    })
  },
  addressIpt(e) {
    this.setData({
      address: e.detail.value
    })
  },
  numIpt(e) {
    this.setData({
      num: e.detail.value
    })
  },
  save() {
    let that = this;
    let name = that.data.name;
    let phone = that.data.phone;
    let address = that.data.address;
    let num = that.data.num;
    let isChecked = that.data.isChecked;
    if (name == "") {
      app.showTip("请填写收货人姓名");
      return;
    } else if (phone == "") {
      app.showTip("请填写收货人手机号");
      return;
    } else if (!that.validatePhoneNumber(phone)) {
      app.showTip("手机号格式错误");
      return;
    } else if (address == "") {
      app.showTip("请填写详细地址");
      return;
    } else if (num == "") {
      app.showTip("请填写门牌号");
      return;
    }

    var is_mr = 0;
    if (isChecked) {
      is_mr = 1;
    }

    //提交数据
    wx.showLoading({
      title: '数据提交中...',
      mask: true
    });

    //发起网络请求
    wx.request({
      url: that.data.baseUrl + 'addOrEditAddressInfo.php',
      method: 'POST',
      data: {
        'openid': that.data.openid,
        'name': name,
        'tel': phone,
        'address': address,
        'room_number': num,
        'is_mr': is_mr,
        'id': that.data.id
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        app.showTip(res.data.msg);
        if (res.data.status == 1) {
          //重新赋值后台请求数据
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            });
          }, 1300)
        } else {
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            });
          }, 1500);
        }
      },
      fail: function () {
        wx.hideLoading();
      }
    });
  },
  validatePhoneNumber(phone) {
    // 去除首尾空格
    const trimmedPhone = phone.trim();
    // 正则验证
    const phoneReg = /^1[3-9]\d{9}$/;
    return phoneReg.test(trimmedPhone);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;

    var id = options.id;
    that.setData({
      id: id
    });


    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getShoppingMallAddOrEditAddressPageInfo(res.data.openid, id);
              },
              fail: function (res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //获取本页数据
      that.getShoppingMallAddOrEditAddressPageInfo(openid, id);
    }

    //调用分享
    that.getShareInfo();
  },

  //获取本页数据
  getShoppingMallAddOrEditAddressPageInfo(openid, id) {
    var that = this;
    wx.showLoading({
      title: '数据加载中...',
      mask: true
    });

    //发起网络请求
    wx.request({
      url: that.data.baseUrl + 'getShoppingMallAddOrEditAddressPageInfo.php',
      method: 'POST',
      data: {
        'openid': openid,
        'id': id
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //重新赋值后台请求数据
          if (parseInt(id) > 0) {
            var addressInfo = res.data.addressInfo;
            that.setData({
              isChecked: parseInt(addressInfo.is_mr),
              name: addressInfo.name,
              phone: addressInfo.tel,
              address: addressInfo.address,
              num: addressInfo.room_number
            });
          }
        } else {
          app.showTip(res.data.msg);
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            });
          }, 1500);
        }
      },
      fail: function () {
        wx.hideLoading();
      }
    });
  },

  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function (res) {}
    });
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/index/index',
      imageUrl: that.data.shareImg,
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})